import 'dart:convert';
import 'package:get/get.dart';
import 'store_util.dart';
import '../bindings/controller_binding.dart';

/// 应用状态管理器
/// 负责处理应用被系统回收后的状态恢复
class AppStateManager {
  static const String _appStateKey = 'app_state';
  static const String _routeHistoryKey = 'route_history';
  static const int _stateExpirationTime = 60 * 60 * 1000; // 1小时

  /// 保存应用当前状态
  static Future<void> saveAppState() async {
    // try {
    //   String currentRoute = Get.currentRoute;
    //
    //   // 安全地处理arguments，可能是任何类型
    //   dynamic rawArguments = Get.arguments;
    //   Map<String, dynamic> arguments = {};
    //
    //   if (rawArguments != null) {
    //     if (rawArguments is Map<String, dynamic>) {
    //       arguments = rawArguments;
    //     } else if (rawArguments is Map) {
    //       // 尝试转换其他类型的Map
    //       arguments = Map<String, dynamic>.from(rawArguments);
    //     } else {
    //       // 对于非Map类型，存储为特殊键值
    //       arguments = {'_raw_argument': rawArguments};
    //     }
    //   }
    //
    //   Map<String, dynamic> appState = {
    //     'currentRoute': currentRoute,
    //     'arguments': arguments,
    //     'timestamp': DateTime.now().millisecondsSinceEpoch,
    //   };
    //
    //   await saveData(_appStateKey, jsonEncode(appState));
    //
    //   // 同时保存路由历史
    //   await _saveRouteHistory(currentRoute);
    //
    //   Get.log('App state saved: $currentRoute');
    // } catch (e) {
    //   Get.log('Failed to save app state: $e');
    // }
  }

  /// 保存路由历史
  static Future<void> _saveRouteHistory(String route) async {
    try {
      String? historyStr = await readData(_routeHistoryKey);
      List<String> history = [];
      
      if (historyStr != null && historyStr.isNotEmpty) {
        List<dynamic> historyJson = jsonDecode(historyStr);
        history = historyJson.cast<String>();
      }
      
      // 添加新路由到历史记录
      if (!history.contains(route)) {
        history.add(route);
        
        // 保持历史记录不超过10个
        if (history.length > 10) {
          history.removeAt(0);
        }
        
        await saveData(_routeHistoryKey, jsonEncode(history));
      }
    } catch (e) {
      Get.log('Failed to save route history: $e');
    }
  }

  /// 恢复应用状态
  static Future<bool> restoreAppState() async {
    // try {
    //   String? appStateStr = await readData(_appStateKey);
    //   if (appStateStr == null || appStateStr.isEmpty) {
    //     Get.log('No app state to restore');
    //     return false;
    //   }
    //
    //   Map<String, dynamic> appState = jsonDecode(appStateStr);
    //   String savedRoute = appState['currentRoute'] ?? '/home';
    //   dynamic arguments = appState['arguments'];
    //   int timestamp = appState['timestamp'] ?? 0;
    //
    //   // 检查状态是否过期
    //   int currentTime = DateTime.now().millisecondsSinceEpoch;
    //   if (currentTime - timestamp > _stateExpirationTime) {
    //     Get.log('App state expired, not restoring');
    //     await clearAppState();
    //     return false;
    //   }
    //
    //   // 检查是否应该恢复该路由
    //   if (!_shouldRestoreRoute(savedRoute)) {
    //     Get.log('Route should not be restored: $savedRoute');
    //     return false;
    //   }
    //
    //   Get.log('Restoring app state to route: $savedRoute');
    //
    //   // 确保控制器被正确初始化
    //   await _ensureControllersInitialized();
    //
    //   // 检查token有效性
    //   String? token = await readData('token');
    //   if (token == null || token.isEmpty) {
    //     Get.log('Token invalid, redirecting to login');
    //     Get.offAllNamed('/login');
    //     return true;
    //   }
    //
    //   // 恢复到保存的路由
    //   if (arguments != null) {
    //     dynamic restoredArguments = _restoreArguments(arguments);
    //     if (restoredArguments != null) {
    //       Get.offAllNamed(savedRoute, arguments: restoredArguments);
    //     } else {
    //       Get.offAllNamed(savedRoute);
    //     }
    //   } else {
    //     Get.offAllNamed(savedRoute);
    //   }
    //
      return true;
    // } catch (e) {
    //   Get.log('Failed to restore app state: $e');
    //   await clearAppState();
    //   return false;
    // }
  }

  /// 恢复参数到原始类型
  static dynamic _restoreArguments(dynamic savedArguments) {
    try {
      if (savedArguments is Map<String, dynamic>) {
        // 检查是否是我们特殊存储的非Map类型参数
        if (savedArguments.containsKey('_raw_argument') && savedArguments.length == 1) {
          return savedArguments['_raw_argument'];
        }
        // 否则返回Map类型参数
        return savedArguments;
      }
      return savedArguments;
    } catch (e) {
      Get.log('Failed to restore arguments: $e');
      return null;
    }
  }

  /// 检查路由是否应该被恢复
  static bool _shouldRestoreRoute(String route) {
    // 不应该恢复的路由
    List<String> excludedRoutes = [
      '/',
      '/login',
      '/initialization',
    ];

    for (String excludedRoute in excludedRoutes) {
      if (route.contains(excludedRoute)) {
        return false;
      }
    }

    return true;
  }

  /// 确保控制器被正确初始化
  static Future<void> _ensureControllersInitialized() async {
    try {
      // 重新绑定全局控制器
      ControllerBinding().dependencies();
      
      // 给控制器一些时间来初始化
      await Future.delayed(const Duration(milliseconds: 100));
      
      Get.log('Controllers reinitialized');
    } catch (e) {
      Get.log('Failed to reinitialize controllers: $e');
    }
  }

  /// 清除保存的应用状态
  static Future<void> clearAppState() async {
    // try {
    //   await removeData(_appStateKey);
    //   Get.log('App state cleared');
    // } catch (e) {
    //   Get.log('Failed to clear app state: $e');
    // }
  }

  /// 获取路由历史
  static Future<List<String>> getRouteHistory() async {
    // try {
    //   String? historyStr = await readData(_routeHistoryKey);
    //   if (historyStr != null && historyStr.isNotEmpty) {
    //     List<dynamic> historyJson = jsonDecode(historyStr);
    //     return historyJson.cast<String>();
    //   }
    // } catch (e) {
    //   Get.log('Failed to get route history: $e');
    // }
    return [];
  }

  /// 清除路由历史
  static Future<void> clearRouteHistory() async {
    try {
      await removeData(_routeHistoryKey);
      Get.log('Route history cleared');
    } catch (e) {
      Get.log('Failed to clear route history: $e');
    }
  }

  /// 检查应用是否可能被回收过
  static Future<bool> wasAppRecycled() async {
    try {
      String? appStateStr = await readData(_appStateKey);
      if (appStateStr == null || appStateStr.isEmpty) {
        return false;
      }

      Map<String, dynamic> appState = jsonDecode(appStateStr);
      String savedRoute = appState['currentRoute'] ?? '/';
      String currentRoute = Get.currentRoute;

      // 如果保存的路由和当前路由不一致，且当前在初始化页面，则可能被回收过
      return savedRoute != currentRoute && currentRoute == '/';
    } catch (e) {
      Get.log('Failed to check if app was recycled: $e');
      return false;
    }
  }
}
